const exp = require('express')
const MD5 = require('md5')
const userModel = require('../db/models/users')
const router = new exp.Router()

router.get('/users/:page/:limit', async (req, res) => {
  try {
    const page = +req.params.page
    const limit = +req.params.limit

    const users = await userModel
      .find({}, { password: 0 })
      .skip((page - 1) * limit)
      .limit(limit)

    const total = await userModel.count()
    res.json({
      code: 20000,
      data: {
        users: users.map((user) => {
          return {
            id: user._id,
            username: user.username,
            nickname: user.nickname,
            createTime: user.createTime,
          }
        }),
        total,
      },
    })
  } catch (e) {
    res.json({
      code: 20001,
      message: '服务器故障',
    })
  }
})

router.post('/users', async (req, res) => {
  try {
    const { username, nickname, password } = req.body
    const isExistUser = await userModel.findOne({ username })
    if (isExistUser) {
      return res.json({
        code: 20002,
        message: '用户名已存在',
      })
    }
    const addUser = await userModel.create({
      username,
      nickname,
      password: MD5(password),
      createTime: Date.now(),
    })
    res.json({
      code: 20000,
      data: {
        id: addUser._id,
        username: addUser.username,
        nickname: addUser.nickname,
      },
      message: '添加成功',
    })
  } catch (e) {
    res.json({
      code: 20001,
      message: '服务器故障',
    })
  }
})

router.put('/users/:id', async (req, res) => {
  try {
    const { username, nickname, password } = req.body
    const { id } = req.params
    const isExistUser = await userModel.findOne({ username, _id: { $ne: id } })
    if (isExistUser) {
      return res.json({
        code: 20002,
        message: '用户名已存在',
      })
    }
    await userModel.updateOne(
      { _id: id },
      { $set: { username, nickname, password: MD5(password) } }
    )
    res.json({
      code: 20000,
      message: '修改成功',
    })
  } catch (e) {
    res.json({
      code: 20001,
      message: '服务器故障',
    })
  }
})

router.delete('/users/:id', async (req, res) => {
  try {
    const { id } = req.params
    await userModel.remove({ _id: id })
    res.json({
      code: 20000,
      message: '删除成功',
    })
  } catch (e) {
    res.json({
      code: 20001,
      message: '服务器故障',
    })
  }
})

module.exports = router
